//
//  STTextView.m
//
//  Created by yls on 14/12/11.
//  Copyright (c) 2014年 yls. All rights reserved.
//

#import "STTextView.h"

@interface STTextView()<UITextViewDelegate>
{
    UITextView *_textView;
    UITextView *_placeholderTextView;
    TextDidChangeBlock _TextDidChangeBlock;
}

@property(nonatomic,assign) id<UITextViewDelegate> delegate;

@end

@implementation STTextView

- (void)dealloc
{
    for (NSString *keyPath in self.keyPaths) {
        [_textView removeObserver:self forKeyPath:keyPath context:nil];
    }
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UITextViewTextDidChangeNotification object:nil];
}

- (instancetype)init
{
    self = [self initWithFrame:CGRectZero];
    if (self) {
        
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        _maxLength = NSUIntegerMax;
        _placeholder = @"";
        
        _placeholderTextView = [[UITextView alloc] init];
        _placeholderTextView.backgroundColor = [UIColor clearColor];
        _placeholderTextView.frame = self.bounds;
        _placeholderTextView.textColor = [UIColor lightGrayColor];
        [self addSubview:_placeholderTextView];
        
        _textView = [[UITextView alloc] init];
        _textView.backgroundColor = [UIColor clearColor];
        _textView.frame = self.bounds;
        _textView.delegate = self;
        _textView.contentInset = UIEdgeInsetsMake(0, 0, 5, 0);
        [self addSubview:_textView];
        
        for (NSString *keyPath in self.keyPaths) {
            [_textView addObserver:self forKeyPath:keyPath options:NSKeyValueObservingOptionInitial | NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];
        }
        
        for (NSString *keyPath in self.selfKeyPaths) {
            [self addObserver:self forKeyPath:keyPath options:NSKeyValueObservingOptionInitial | NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];
        }
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textChanged:) name:UITextViewTextDidChangeNotification object:nil];
    }
    return self;
}

#pragma mark property set & get

//- (void)setDelegate:(id<UITextViewDelegate>)delegate
//{
//    _textView.delegate = delegate;
//}
//
//- (id<UITextViewDelegate>)delegate
//{
//    return _textView.delegate;
//}

- (void)setText:(NSString *)text
{
    _textView.text = text;
}

- (NSString *)text
{
    return _textView.text;;
}

- (void)setFont:(UIFont *)font
{
    _textView.font = font;
}

- (UIFont *)font
{
    return _textView.font;
}

- (void)setTextColor:(UIColor *)textColor
{
    _textView.textColor = textColor;
}

- (UIColor *)textColor
{
    return _textView.textColor;
}

- (void)setTextAlignment:(NSTextAlignment)textAlignment
{
    _textView.textAlignment = textAlignment;
}

- (NSTextAlignment)textAlignment
{
    return _textView.textAlignment;
}

- (void)setSelectedRange:(NSRange)selectedRange
{
    _textView.selectedRange = selectedRange;
}

- (NSRange)selectedRange
{
    return _textView.selectedRange;
}

- (void)setEditable:(BOOL)editable
{
    _textView.editable = editable;
}

- (BOOL)isEditable
{
    return _textView.isEditable;
}

- (void)setSelectable:(BOOL)selectable
{
    _textView.selectable = selectable;
}

- (BOOL)isSelectable
{
    return _textView.isSelectable;
}

- (void)setBackgroundColor:(UIColor *)backgroundColor
{
    _placeholderTextView.backgroundColor = backgroundColor;
}

- (void)textChanged:(NSNotification *)noti
{
    if (noti.object == _textView) {
        if (self.text.length == 0) {
            _placeholderTextView.text = _placeholder;
        } else {
            _placeholderTextView.text = @"";
        }
        if (_TextDidChangeBlock) {
            _TextDidChangeBlock(_textView);
        }
    }
}

- (void)setTextDidChangeBlock:(void (^)(UITextView *))TextDidChangeBlock;
{
    _TextDidChangeBlock = TextDidChangeBlock;
}

- (NSArray *)keyPaths
{
    return @[ @"font", @"frame" ];
}

- (NSArray *)selfKeyPaths
{
    return @[ @"placeholder", @"text" ];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if ([keyPath isEqualToString:@"text"]) {
        if (self.text.length == 0) {
            _placeholderTextView.text = _placeholder;
        } else {
            _placeholderTextView.text = @"";
        }
    } else if ([keyPath isEqualToString:@"font"]) {
        _placeholderTextView.font = _textView.font;
    } else if ([keyPath isEqualToString:@"frame"]) {
        _textView.frame = self.bounds;
        _placeholderTextView.frame = _textView.frame;
    } else if ([keyPath isEqualToString:@"placeholder"]) {
        _placeholderTextView.text = self.placeholder;
    }
}

#pragma mark - UITextView Delegate

- (BOOL)textViewShouldBeginEditing:(UITextView *)textView;
{
    if (_delegate && [_delegate respondsToSelector:@selector(textViewShouldBeginEditing:)]) {
        return [_delegate textViewShouldBeginEditing:_textView];
    }
    return YES;
}

- (BOOL)textViewShouldEndEditing:(UITextView *)textView;
{
    if (_delegate && [_delegate respondsToSelector:@selector(textViewShouldEndEditing:)]) {
        return [_delegate textViewShouldEndEditing:_textView];
    }
    return YES;
}

- (void)textViewDidBeginEditing:(UITextView *)textView;
{
    if (_delegate && [_delegate respondsToSelector:@selector(textViewDidBeginEditing:)]) {
        [_delegate textViewDidBeginEditing:_textView];
    }
}

- (void)textViewDidEndEditing:(UITextView *)textView;
{
    if (_delegate && [_delegate respondsToSelector:@selector(textViewDidEndEditing:)]) {
        [_delegate textViewDidEndEditing:_textView];
    }
}
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text;
{
    if (_delegate && [_delegate respondsToSelector:@selector(textView:shouldChangeTextInRange:replacementText:)]) {
        return [_delegate textView:_textView shouldChangeTextInRange:range replacementText:text];
    } else {
        if (textView == _textView) {
            if (text.length > 0 && textView.text.length + text.length > _maxLength + 10) {
                NSMutableString *view_text = [NSMutableString stringWithString:textView.text];
                NSInteger length = textView.text.length;
                [view_text insertString:[text substringToIndex:_maxLength-length] atIndex:range.location];
                textView.text = view_text;
                if (_textView.text.length == 0) {
                    _placeholderTextView.text = _placeholder;
                } else {
                    _placeholderTextView.text = @"";
                }
                if (_TextDidChangeBlock) {
                    _TextDidChangeBlock(_textView);
                }
                return NO;
            }
        }
    }
    return YES;
}

- (void)textViewDidChange:(UITextView *)textView;
{
    if (textView.text.length > _maxLength) {
        textView.text = [textView.text substringToIndex:_maxLength];
    }
    if (_delegate && [_delegate respondsToSelector:@selector(textViewDidChange:)]) {
        [_delegate textViewDidChange:_textView];
    }
}

- (void)textViewDidChangeSelection:(UITextView *)textView;
{
    if (_delegate && [_delegate respondsToSelector:@selector(textViewDidChangeSelection:)]) {
        [_delegate textViewDidChangeSelection:_textView];
    }
}

- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange NS_AVAILABLE_IOS(7_0);
{
    if (_delegate && [_delegate respondsToSelector:@selector(textView:shouldInteractWithURL:inRange:)]) {
        return [_delegate textView:_textView shouldInteractWithURL:URL inRange:characterRange];
    } else {
        
    }
    return YES;
}

- (BOOL)textView:(UITextView *)textView shouldInteractWithTextAttachment:(NSTextAttachment *)textAttachment inRange:(NSRange)characterRange NS_AVAILABLE_IOS(7_0);
{
    if (_delegate && [_delegate respondsToSelector:@selector(textView:shouldInteractWithTextAttachment:inRange:)]) {
        return [_delegate textView:_textView shouldInteractWithTextAttachment:textAttachment inRange:characterRange];
    } else {
        
    }
    return YES;
}

#pragma mark - UITextInputTraits

- (void)setSpellCheckingType:(UITextSpellCheckingType)spellCheckingType
{
    _textView.spellCheckingType = spellCheckingType;
}

- (UITextSpellCheckingType)spellCheckingType
{
    return _textView.spellCheckingType;
}

- (void)setAutocorrectionType:(UITextAutocorrectionType)autocorrectionType
{
    _textView.autocorrectionType = autocorrectionType;
}

- (void)setUserInteractionEnabled:(BOOL)userInteractionEnabled
{
    _textView.userInteractionEnabled = userInteractionEnabled;
}

- (BOOL)isUserInteractionEnabled
{
    return _textView.userInteractionEnabled;
}

#pragma mark - other

- (BOOL)resignFirstResponder
{
    return [_textView resignFirstResponder];
}

@end
